<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>列表列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="15">
          <el-input
            placeholder="请输入内容"
            v-model="querInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addBtnData"
            >添加按钮</el-button
          ></el-col
        >
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="油箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.mg_state"
              @change="stateChenge(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template>
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色按钮 -->

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addformRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <!-- <el-input v-model="addForm.password"></el-input> -->
          <el-input
            v-model="addForm.password"
            show-password
            clearable
            @clear="getUserList"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确认区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'Users',
  data () {
    //   验证账号
    var checkUsername = (rule, value, cb) => {
      const regUsername = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
      if (regUsername.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的账号'))
    }
    // 验证密码
    var checkPassword = (rule, value, cb) => {
      const regUsername = /^[a-zA-Z]\w{5,17}$/
      if (regUsername.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的密码'))
    }
    // 验证油箱
    var checkEmail = (rule, value, cb) => {
      const regUsername = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regUsername.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的油箱'))
    }
    // 验证手机号
    var checkMobile = (rule, value, cb) => {
      const regUsername = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/
      if (regUsername.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 用户列表的参数
      querInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      //  获取完整的表单
      userlist: [],
      //  获取表单的页数
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addformRules: {
        //   验证账号
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        // 验证油箱
        email: [
          { required: true, message: '请输入油箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 验证手机号
        mobile: [
          { required: true, message: '请输入油箱', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    //  生命周期
    this.getUserList()
  },
  methods: {
    //  axios获取用户的列表
    async getUserList () {
      const res = await this.$http.get('/users', {
        params: this.querInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      //   console.log(res)
    },
    // 监听pagesize 改变事件
    handleSizeChange (newSize) {
      this.querInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值的改变事件
    handleCurrentChange (newpage) {
      this.querInfo.pagenum = newpage
      this.getUserList()
    },
    // 监听switch开关状态的改变
    async stateChenge (userinfo) {
      const res = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        this.userinfo.mg_state = !this.userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 显示添加框
    addBtnData () {
      this.addDialogVisible = true
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户发送axios请求
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户状态失败！')
        }
        this.$message.success('成功用户状态成功！')
        this.addDialogVisible = false
        this.getUserList()
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
